/*
 * Copyright 2011-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0.
 * See `LICENSE` in the project root for license information.
 */

package me.ijleex.jmh.benchmark.counter.impl;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import me.ijleex.jmh.benchmark.counter.Counter;

/**
 * ReadWriteLockCounter.
 *
 * @author liym
 * @since 2020-05-27 12:20 新建
 */
public class ReadWriteLockCounter implements Counter {

    private final Lock readLock;
    private final Lock writeLock;

    private long counter;

    /**
     * @param fair 是否使用公平锁
     */
    public ReadWriteLockCounter(boolean fair) {
        ReadWriteLock lock = new ReentrantReadWriteLock(fair);
        this.readLock = lock.readLock();
        this.writeLock = lock.writeLock();
    }

    @Override
    public void increment() {
        this.writeLock.lock();
        try {
            ++this.counter;
        } finally {
            this.writeLock.unlock();
        }
    }

    @Override
    public long getCount() {
        this.readLock.lock();
        try {
            return this.counter;
        } finally {
            this.readLock.unlock();
        }
    }

}
